const assert = require('node:assert');
const { encode } = require('@jridgewell/sourcemap-codec');
const { SourceMapConsumer } = require('source-map');
const getLocation = require('../../getLocation');
const originalCode = `
export function App() {
  if (count) {
    console.log(count);
  }
  return <div>{count}</div>;
}
`;

module.exports = defineTest({
	description: 'get correct combined sourcemap of bundled code',
	formats: ['es'],
	options: {
		external: ['react/jsx-runtime'],
		plugins: [
			{
				resolveId(id) {
					return id;
				},
				load() {
					return {
						code: originalCode
					};
				}
			},
			{
				async transform(code) {
					// returned code and mappings generated by esbuild@0.25.5
					return {
						code: `export function App() {
  if (count) {
    console.log(count);
  }
  return /* @__PURE__ */ React.createElement("div", null, count);
}
`,
						map: {
							mappings: encode([
								[
									[0, 0, 1, 7],
									[16, 0, 1, 16],
									[22, 0, 1, 22]
								],
								[
									[0, 0, 2, 2],
									[6, 0, 2, 6],
									[13, 0, 2, 13]
								],
								[
									[0, 0, 3, 4],
									[12, 0, 3, 12],
									[16, 0, 3, 16],
									[21, 0, 3, 21]
								],
								[
									// coarse segment
									[0, 0, 3, 21],
									[2, 0, 4, 2]
								],
								[
									[0, 0, 5, 2],
									[9, 0, 5, 9],
									[45, 0, 5, 10],
									[58, 0, 5, 15],
									[63, 0, 5, 21]
								],
								[[0, 0, 6, 0]],
								[]
							]),
							names: [],
							sourcesContent: [code]
						}
					};
				}
			}
		]
	},
	async test(code, map) {
		const generatedLoc = getLocation(code, code.indexOf('  }') + 2);
		const smc = await new SourceMapConsumer(map);
		const originalLoc = smc.originalPositionFor(generatedLoc);
		const expectedOriginalLoc = getLocation(originalCode, originalCode.indexOf('  }') + 2);
		console.log(originalLoc, expectedOriginalLoc);
		assert.equal(originalLoc.line, expectedOriginalLoc.line);
		assert.equal(originalLoc.column, expectedOriginalLoc.column);
	}
});
